using System;
using System.Diagnostics;
using Me.Prettyprint.Cassandra.Utils;

namespace Me.Prettyprint.Cassandra.Connection
{
    /// <summary>
    /// MetricsOpTimer is a simple timer that measures operation elapsed time
    /// using C# StopWatch class.
    /// </summary>
	public class MetricsOpTimer : HOpTimer
	{
        private const string TIMER_TYPE = "hector";

        public MetricsOpTimer(MetricsRegistry metricsRegistry, string clusterName, TimeUnit durationUnit, TimeUnit rateUnit)
        {
            MetricsRegistry = metricsRegistry;
            ClusterName = clusterName;
            DurationUnit = durationUnit;
            RateUnit = rateUnit;
        }
        public MetricsOpTimer(string clusterName)
        {
            MetricsRegistry = new MetricsRegistry();
            ClusterName = clusterName;
            DurationUnit = TimeUnit.NANOSECONDS;
            RateUnit = TimeUnit.SECONDS;
        }
        public TimeUnit DurationUnit
        {
            get;
            private set;
        }
        public TimeUnit RateUnit
        {
            get;
            private set;
        }
        public MetricsRegistry MetricsRegistry
        {
            get;
            private set;
        }
        public string ClusterName
        {
            get;
            private set;
        }
        public Object Start(string tagName)
        {
            Stopwatch watch = new Stopwatch();
            Timer timer = MetricsRegistry.NewTimer(new MetricName(ClusterName, TIMER_TYPE, tagName), DurationUnit, RateUnit);
            return timer.Time();
        }
        public void Stop(object token, string tagName, bool success)
        {
            TimerContext timerContext = (TimerContext) token;
            timerContext.Stop();
        }
	}
}